package com.amanda.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author amanda
 * @Description 自定义异常处理器
 * 全局异常捕获
 */
@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    /**
     * 自定义异常处理方法
     * @param ex 当前异常
     * @return R<String>
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.info("异常信息："+ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")) {
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "用户已存在！";
            return R.error(msg);
        }
        return R.error("未知错误，请联系程序员处理！");
    }

    /**
     * 自定义异常处理方法
     * @param ex 当前异常
     * @return R<String>
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex) {
        log.info("异常信息："+ex.getMessage());
        return R.error(ex.getMessage());
    }

}
